/**
 * Created by mooshroom on 2017/1/11.
 */
var foodTypes = [

    {
        TypeID: "1",
        foodTotal: 0,
        icon: "谷",
        color: "#f3c280",
        Name: "谷类薯类及杂豆",
        TargetWeightMin: "250.00",
        TargetWeightMax: "400.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "2",
        foodTotal: 0,
        icon: "豆",
        color: "#b14e34",
        Name: "大豆类及坚果",
        TargetWeightMin: "25.00",
        TargetWeightMax: "35.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "3",
        foodTotal: 0,
        icon: "蔬",
        color: "#8ea53a",
        Name: "蔬菜类",
        TargetWeightMin: "300.00",
        TargetWeightMax: "500.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "4",
        foodTotal: 0,
        icon: "果",
        color: "#f4a001",
        Name: "水果类",
        TargetWeightMin: "200.00",
        TargetWeightMax: "350.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "5",
        foodTotal: 0,
        icon: "肉",
        color: "#de4d36",
        Name: "畜禽肉类",
        TargetWeightMin: "40.00",
        TargetWeightMax: "75.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "6",
        foodTotal: 0,
        icon: "奶",
        color: "#66aee8",
        Name: "奶类及奶制品",
        TargetWeightMin: "250.00",
        TargetWeightMax: "350.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "7",
        foodTotal: 0,
        icon: "蛋",
        color: "#f8d03e",
        Name: "蛋类",
        TargetWeightMin: "25.00",
        TargetWeightMax: "50.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "8",
        foodTotal: 0,
        icon: "鱼",
        color: "#f97f52",
        Name: "鱼虾类",
        TargetWeightMin: "50.00",
        TargetWeightMax: "100.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "9",
        foodTotal: 0,
        icon: "油",
        color: "#870e03",
        Name: "油",
        TargetWeightMin: "25.00",
        TargetWeightMax: "30.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "10",
        foodTotal: 0,
        icon: "盐",
        color: "#c8c8c8",
        Name: "盐",
        TargetWeightMin: "0.00",
        TargetWeightMax: "6.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
    {
        TypeID: "11",
        foodTotal: 0,
        icon: "另",
        color: "#f1f1f1",
        Name: "其他",
        TargetWeightMin: "0.00",
        TargetWeightMax: "2000.00",
        wanting: false,
        want: [0, 0, 0],
        mealTotal: [0, 0, 0]
    },
]


var historyList=[]
/**
 * Created by mooshroom on 2015/12/11.
 */
/*………………………………………………………………………………………………全局配置………………………………………………………………………………………………*/
// var apiURL = './index.php?i=';
var URL = window.location.protocol+'//www.tandanzhi.com/'
var apiURL = window.location.protocol+'//www.tandanzhi.com/sf.php?i=' //开发版服务端
//var apiURL = 'http://www.huiruo.cn/index.php?i='  //生产版
if(window.location.host=='this'||window.location.host=='localhost'){
    apiURL = window.location.protocol+'//tdz.dev.tansuyun.cn/sf.php?i=' //开发版服务端
}

require(['../../plugins/wxSDK/wxsdk2.js'],function (sdk) {
    sdk()
})
/*
 * 注意：
 * 1. 所有的JS接口只能在公众号绑定的域名下调用，公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
 * 2. 如果发现在 Android 不能分享自定义内容，请到官网下载最新的包覆盖安装，Android 自定义分享接口需升级至 6.0.2.58 版本及以上。
 * 3. 完整 JS-SDK 文档地址：http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
 *
 * 如有问题请通过以下渠道反馈：
 * 邮箱地址：weixin-open@qq.com
 * 邮件主题：【微信JS-SDK反馈】具体问题
 * 邮件内容说明：用简明的语言描述问题所在，并交代清楚遇到该问题的场景，可附上截屏图片，微信团队会尽快处理你的反馈。
 */
try {
    wx.ready(function () {
        // tip.on("微信SDK接入成功",1,700)
    })
    wx.error(function (res) {
        // tip.on(JSON.stringify(res));
    });
} catch (err) {
}

//cache.go({
//    tsy: ""
//})
//doorWX.getCode();

/*………………………………………………………………………………………………index的视图模型………………………………………………………………………………………………*/
require([
    'avalon',
    'mmRequest',
    //'../../plugins/door/door.js',
    'text!../../nav.json',
    //'../../lib/pop/popAlert.js',
    '../../plugins/Gate/Gate.wechat.js',
], function (avalon, mmRequest, nav,newGate) {
    var vm = avalon.define({
        $id: "index",
        ready: function () {

            console.time("路由加载时间");
            //构建路由
            require([
                "mmRouter",
            ], function () {
                console.timeEnd("路由加载时间");
                avalon.router.get("/", function () {
                    goto('#!/Login_wx/0')
                });
                var navList = JSON.parse(nav).nav;
                //构建导航的路由
                getMap(navList);
                console.log("路由构建完毕")

                //发起请求获取用户信息
                vm.getUser(function () {
                    //开始监听
                    console.time("门禁配置时间");
                    window.Gate = newGate({
                        autoLoginAPI: "Diet/User/loginByOpenID",//进行验证的接口编号
                        haveLogin: function (res) {
                            console.log("成功登录");

                        },
                        notLogin: function (res) {
                            // console.log("成功登录");

                        }
                    });
                    avalon.history.start();
                    avalon.scan();
                })


                console.time("缓存设置时间");
                vm.uid = cache.go('UID')
                vm.un = cache.go('Name')

                var g = cache.go('G')
                if (g == undefined) {
                    vm.G = []
                    return
                }
                vm.G = addUp(cache.go('G').split(','))
                console.timeEnd("缓存设置时间");
            })







            vm.$watch('html', function () {
                vm.contentHeight = 0
                vm.contentOpacity = 0
                vm.contentMT = -300
                setTimeout(function () {
                    vm.contentHeight = 'auto'
                    vm.contentOpacity = 1
                    vm.contentMT = 0
                }, 250)
            })


        },
        reset: function () {

        },


        getUser: function (callback) {
            var config={
                success: function (res) {
                    callback()
                    cache.go(res)
                },
                error: function (err) {
                    callback()
                    console.error('用户信息获取失败:'+err)
                }
            }

            var url=location.protocol + '//r.tansuyun.cn/w.php?i=Js/getLogined'
            var rtsy=cache.go('rtsy')
            if(rtsy!=undefined&&String(rtsy).length>0&&rtsy!='undefined'){
                url+='&tsy=' + rtsy;
            }
            avalon.ajax({
                url:url,
                type:'post',
                data:{},
                success: function (res) {
                    //如果自动转换失败则手动转换一次json
                    if (typeof res == "string") {
                        res = JSON.parse(res)
                    }

                    if (!res.err && res.d !== false) {
                        //执行成功
                        config.success(res.d, res)
                    }
                    else {
                        //执行失败

                        config.error(res.err)

                        console.log('服务端执行错误：' + res.m)
                        console.log(res)
                    }

                    // //缓存tsy
                    // if (res.tsy) {
                    //     cache.go({tsy: res.tsy})
                    // }



                    //缓存用户登录信息
                    if (res.UID > 0) {
                        //已登录状态
                        cache.go({
                            uid: res.UID,
                            un: res.UN
                        })
                        try {
                            Gate.logined = true
                        } catch (err) {
                        }
                    } else {
                        //未登录或登陆已失效
                        try {
                            Gate.reset()
                        } catch (err) {
                        }
                        index.uid = 0
                    }

                    cache.go({
                        rtsy:res.tsy
                    })
                }
            })
        },

        lib: "",
        //当前用户的信息
        contentMT: "0",
        contentHeight: 'auto',
        contentOpacity: 1,
        admin: false,
        uid: "",
        un: "",
        G: "",
        g: "", //用户切换页面标记
        showHomeBtn:false,
        showLoginBtn:false,
        //切换到后台的时候调用的方法
        // toggleSide: function (i) {
        //     switch (i) {
        //         case 0:
        //             //跳转到前台
        //             vm.nav = vm.CoachNav
        //             window.location.href = '#!/Home/0'
        //             vm.g = 1
        //             break
        //         case 1:
        //             //跳转到后台
        //             vm.nav = vm.AdminNav
        //             window.location.href = '#!/CoachList/0'
        //             vm.g = 2
        //             break
        //     }
        // },
        //登出
        logout: function () {
            $$.call({
                    i: 'User/logout',
                    data: {},
                    success: function (res) {
                        window.location.href = "#!/Login_wx/0"
                        Gate.reset()
                        index.uid = ""
                    },
                    err: function (err) {
                        tip.on(err, 1)
                    }
                }
            )
        },
        //jumpToMember:function(){
        //    for(var i = 0; i < vm.G.length; i++){
        //        //if(window.location.href=='#!/CoachList/0'){
        //            if(vm.G[i]==1){
        //                vm.toggleSide(0)
        //                vm.g=1
        //            }
        //        //}
        //    }
        //},
        //jumpToCoach:function(){
        //for(var i = 0; i < vm.G.length; i++) {
        //    //if (window.location.href == '#!/MemberList/0') {
        //        if (vm.G[i] == 2) {
        //            vm.toggleSide(1)
        //            vm.g = 2
        //        //}
        //    }
        //}
        //},

        // 控制姓名的下拉框
        showNameDropdown: false,
        SNDTimeout: "",
        /*
         * toggleND 控制姓名下拉框的出现和小时
         * @param i ：0-消失；1-出现；2-自动
         * */
        toggleND: function (i) {
            clearTimeout(vm.SNDTimeout)

            switch (i) {
                case 0:
                    vm.SNDTimeout = setTimeout(function () {
                        vm.showNameDropdown = false;
                    }, 400)
                    break
                case 1:
                    vm.showNameDropdown = true;
                    break
                case 2:
                    vm.showNameDropdown = !vm.showNameDropdown
            }
        },

        //启动页面的开启和关闭
        inFrontPage:true,
        getIn: function () {
            vm.inFrontPage=false
        },


        html: '',
        nowTop: '',

        //导航条
        nav: [{
            name: "",
            en: "",
            href: ""
        }],
        CoachNav: [
            // {
            //     name: "我的主页",
            //     en: "Home",
            //     href: "#!/Home/0&&&&"
            // }, {
            //     name: "食谱库",
            //     en: "DietList",
            //     href: "#!/DietList/1&&&&"
            // }, {
            //     name: "食物成分表",
            //     en: "FoodList",
            //     href: "#!/FoodList/1&&&&"
            // }
        ],
        AdminNav: [
            // {
            //     name: "用户管理",
            //     en: "CoachList",
            //     href: "#!/CoachList/1&&&&"
            // },
            // //{
            // //    name: "俱乐部",
            // //    en: "ClubList",
            // //    href: '#!/ClubList/1&&&&',
            // //},
            // {
            //     name: "食物成分管理",
            //     en: "FoodManage",
            //     href: '#!/FoodManage/1'
            // },
            // {
            //     name: "食物替换表管理",
            //     en: "FoodReplace",
            //     href: '#!/FoodReplace/0'
            // }
        ],

        //组件配置
        //提示框配置
        $opta: {
            id: "tip"
        },
//                模态框配置
//        $optb: {
//            id: "modal"
//        },
        //websocket配置
//        $optc: {
//            id: "ws",
//            server: "ws://180.97.81.190:46032",//线上版本
////                    server: "ws://my.s.tansuyun.cn:46080",//测试版本
//            debug: false
//        },
        $optd: {
            id: "pb"
        },
        //$optTop: {
        //    id: "toTop"
        //},
        $optpop: {
            id: 'pop',
            width: "960",
        },
        $optpop2: {
            id: 'pop2',
            width: "560",
        },
        foodKey: '',

        $opt_ba:{
            id:'bottomAlert',
            height:'366px'
        }

    })

    console.time('基础组件加载时间')
    require([
        '../../lib/tip/tip.js',
        '../../lib/progressbar/progressbar.js',
        '../../lib/bottomAlert/bottomAlert'
    ], function () {
        avalon.nextTick(function () {
            console.timeEnd("基础组件加载时间");
            avalon.scan();
            vm.ready()

            //非必须组件加载
            console.time('额外组件加载')
            require([
                //'../../lib/food_search/food_search.js',
                '../../plugins/shortcut/shortcut',], function () {
                console.timeEnd('额外组件加载')

                //setTimeout(testPop,1000)

                TimerMember()
            })
        })

    })

    window.index = vm

    /*………………………………………………………………………………………………路由处理函数………………………………………………………………………………………………*/

    /*路由*/
    function newRouter(n) {
        console.time(n.name + "路由创建耗时")
        var en = n.en;
        n.vm = '../../package/' + en + "/" + en + '.js'
        avalon.router.get('/' + en + '/:i', function (i) {
            vm.showLoginBtn=false
            historyList.unshift(location.href)
            console.time('模块打开时间')
            //检查权限
            if (n.only > 0) {
                Gate.comeIn({
                    haveLogin: function (res) {

                        //做权限判断
                        var g = res.G

                        for (var i = 0; i < g.length; i++) {
                            if (n.only <= g[i]) {
                                loadVM()
                                return
                            }
                        }

                        if(res.G.length==0){
                            loadVM()
                            return
                        }

                        goto('#!/Login_wx/0')


                    },
                    notLogin: function () {
                        goto('#!/Login_wx/0')
                    }
                })

            } else {
                Gate.comeIn({
                    haveLogin: function (res) {

                    },
                    notLogin: function () {

                        if(en=='Login_wx'){
                            return

                        }

                        vm.showLoginBtn=true
                    }
                })
                loadVM()
            }


            function loadVM() {
                //统计当前页面
                // try{
                //     _hmt.push(['_trackPageview', '/#!/'+n.en+'/'+i+'?page='+ n.name])
                //     _czc.push(['_trackPageview', '/#!/'+n.en+'/'+i+'?page='+ n.name])
                // }catch(err){}

                //开启进度条
                try {
                    pb.startT()
                } catch (err) {

                }

                //if (n.name != "登陆") {
                //    document.getElementById("title").innerText = n.name
                //} else {
                //    document.getElementById("title").innerText = '碳蛋知'
                //}

                //tip.on("正在加载……",1)
                if (n.vm) {
                    require([n.vm], function () {
                        index.showHomeBtn=false
                        avalon.vmodels[en].ready(i)
                        share()
                        index.nowTop = n.bePartOf
                        if (n.font) {
                            vm.nav = vm.CoachNav
                            vm.g = 1
                        } else {
                            vm.nav = vm.AdminNav
                            vm.g = 2
                        }
                        //tip.off("正在加载……",1)\
                        try{
                            if (pop.state != 0) {
                                pop.close()
                            }
                        }catch (err){}

                        //结束进度条
                        try {
                            pb.endT()
                        } catch (err) {
                        }
                    })
                }
                if (n.fn) {
                    n.fn(i)

                    //结束进度条
                    try {
                        pb.endT()
                    } catch (err) {
                    }
                }


                console.log(n.name + "模块加载完毕")
                console.timeEnd('模块打开时间')
            }

        });
        console.timeEnd(n.name + "路由创建耗时")
    }

    function getMap(nav) {
        console.time("路由写入时间")
        var l = nav
        var ll = l.length
        var lsl;
        for (var i = 0; i < ll; ++i) {
            //直接渲染项目
            newRouter(l[i])
        }
        console.timeEnd("路由写入时间")
    }


})



/*………………………………………………………………………………………………全局函数………………………………………………………………………………………………*/
//跨浏览器事件对象方法
var EventUtil = new Object;
EventUtil.addEventHandler = function (oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = fnHandler;
    }
};

EventUtil.removeEventHandler = function (oTarget, sEventType, fnHandler) {
    if (oTarget.removeEventListener) {
        oTarget.removeEventListener(sEventType, fnHandler, false);
    } else if (oTarget.detachEvent) {
        oTarget.detachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = null;
    }
};

EventUtil.formatEvent = function (oEvent) {
    //if (isIE && isWin) {
    //    oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
    //    oEvent.eventPhase = 2;
    //    oEvent.isChar = (oEvent.charCode > 0);
    //    oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
    //    oEvent.pageY = oEvent.clientY + document.body.scrollTop;
    //    oEvent.preventDefault = function () {
    //        this.returnValue = false;
    //    };
    //
    //    if (oEvent.type == "mouseout") {
    //        oEvent.relatedTarget = oEvent.toElement;
    //    } else if (oEvent.type == "mouseover") {
    //        oEvent.relatedTarget = oEvent.fromElement;
    //    }
    //
    //    oEvent.stopPropagation = function () {
    //        this.cancelBubble = true;
    //    };
    //
    //    oEvent.target = oEvent.srcElement;
    //    oEvent.time = (new Date).getTime();
    //}
    return oEvent;
};

EventUtil.getEvent = function () {
    if (window.event) {
        return this.formatEvent(window.event);
    } else {
        return EventUtil.getEvent.caller.arguments[0];
    }
}

EventUtil.getWhellDalta = function () {
    if (event.wheelDelta) {
        return (client.engine.opera && client.engine.opera < 9.5 ?
            -event.wheelDelta : event.wheelDelta);
    } else {
        return -event.detail * 40;
    }
}

//批量绑定快捷键
function bindK(obj) {
    require(['../../plugins/shortcut/shortcut.js'], function () {
        /*快捷键设置*/

        var x
        for (x in obj) {
            if (x.charAt(0) != "$") {
                if (obj.$opt != undefined) {
                    shortcut.add(x, obj[x], obj.$opt)
                } else {
                    shortcut.add(x, obj[x])
                }

                //console.log(x + "快捷键绑定成功")
            }

        }
    })
}

//批量删除快捷键
function removeK(obj) {
    require(['../../plugins/shortcut/shortcut.js'], function () {
        /*快捷键设置*/

        var x
        for (x in obj) {
            if (x.charAt(0) != "$") {
                shortcut.remove(x)
                //console.log(x + "已解除绑定")
            }

        }
    })
}

//安全相加 把所传入的数组的每一项转化为数值然后相加，返回加的结果
function addUp(arr) {
    var result = 0
    for (var i = 0; i < arr.length; i++) {
        result += Number(arr[i])
    }
    return result
}

//输入框输入限制
function minNumber(el) {
    if (el.value == "" || el.value < 0) {
        el.value = ""
    }
}

/*根据时间戳获取字符串*/
function getDateFromTimestamp(Timestamp) {
    for (var i = Timestamp.length; i < 13; i++) {
        Timestamp += '0';
    }
    var date = new Date();
    date.setTime(Timestamp);

    var month = (date.getMonth() + 1) + ''
    for (var o = month.length; o < 2; o++) {
        month = '0' + month
    }
    var day = date.getDate() + ''
    for (var p = day.length; p < 2; p++) {
        day = '0' + day
    }
    return date.getFullYear() + "-" + month + "-" + day
}

//根据字符串获取时间戳
function newDateAndTime(dateStr) {
    var ds = dateStr.split(" ")[0].split("-");
    var ts = dateStr.split(" ")[1] ? dateStr.split(" ")[1].split(":") : ['00', '00', '00'];
    var r = new Date();
    r.setFullYear(ds[0], ds[1] - 1, ds[2]);
    r.setHours(ts[0], ts[1], ts[2], 0);
    return r;
}

//遍历数组和对象
/*
 * for each 语句，
 * 实现for 和for(var i in y)的功能
 * 调用时
 ForEach(obj,function(i){
 })
 * */
function ForEach(obj, func) {
    if (typeof obj == "object") {
        if (obj.length == undefined) {
            for (var x in obj) {
                //传入（每一项，每一项的序列号）
                func(obj[x], x);
            }
        } else {
            for (var i = 0; i < obj.length; i++) {
                //传入（每一项，每一项的序列号）
                func(obj[i], i);
            }
        }
    } else {
        console.log('类型错误:' + JSON.stringify(obj))
    }
}

//计算每日推荐能量摄入
function getGoodEnergy(target, weight, targetWeight) {
    var goodEnergy = 0
    switch (Number(target)) {
        case 1:
            goodEnergy = targetWeight * 30
            break
        case 2:
            goodEnergy = weight * 50
            break
        case 3:
            goodEnergy = weight * 40
            break
    }
    return goodEnergy
}

//界面跳转的封装函数
function goto(href) {
    window.location.href = href
}

//列表类页面的参数构建
function buildListParams(p, k, t) {
    var params = []
    params.push(p)
    params.push(k)
    params.push(t.join("_"))
    return params.join("&&")
}

//获取滚动高度、屏幕高度、可滚动文本总高度
function getScrollInfo() {
    var scrollTop = 0;
    var clientHeight = 0;
    var scrollHeight = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    } else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);

    //console.log(scrollTop + ',' + clientHeight + ',' + scrollHeight)
    return {
        scrollTop: scrollTop,
        clientHeight: clientHeight,
        scrollHeight: scrollHeight,
    }
}

//转换为10为时间戳发送给后端
/*
 * s 要进行转换的时间戳
 * u 转换后的时间单位 字符串 'ms' 毫秒 's' 秒
 * */
function timeLengthFormat(s, u) {
    switch (u) {
        case 'ms':

            return Math.ceil(s * 1000)
            break
        case 's':
            return Math.ceil(s / 1000)

            break
    }
}

//安全赋值，用于解决服务端在字段为空时返回的空数组无法复制给原本设计为对象格式的字段问题
function safeMix(to, from) {
    ForEach(from, function (el, key) {
        try {
            to[key] = from[key]
        } catch (err) {
            console.log(err)
        }
    })

    return to
}


//测试popAlert组件的韩素
function testPop() {
    pop.open('233')
    setTimeout(function () {
        if (document.querySelector('.state-2')) {
            console.log(document.querySelector('.pop-bg'))
            setTimeout(function () {
                window.location.reload()
            }, 100)

        } else {
            ('出错啦')
        }
    }, 500)

}

//用来更新会员的状态的函数
function TimerMember(){
    $$.call({
        i:"Timer/member",
        data:{},
        success: function () {

        },
        error: function () {

        }
    })

}


//获取元素x坐标
function getElementLeft(element){
    var actualLeft = element.offsetLeft;
    var current = element.offsetParent;
    while (current !== null){
        actualLeft += current.offsetLeft;
        current = current.offsetParent;
    }
    return actualLeft;
}
//获取元素Y坐标
function getElementTop(element){
    var actualTop = element.offsetTop;
    var current = element.offsetParent;
    while (current !== null){
        actualTop += current.offsetTop;
        current = current.offsetParent;
    }
    return actualTop;
}

//根据参数返回距离今天的某一天的时间
function strtotime(text, now) {
    //  discuss at: http://phpjs.org/functions/strtotime/
    //     version: 1109.2016
    // original by: Caio Ariede (http://caioariede.com)
    // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // improved by: Caio Ariede (http://caioariede.com)
    // improved by: A. Mat��as Quezada (http://amatiasq.com)
    // improved by: preuter
    // improved by: Brett Zamir (http://brett-zamir.me)
    // improved by: Mirko Faber
    //    input by: David
    // bugfixed by: Wagner B. Soares
    // bugfixed by: Artur Tchernychev
    //        note: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)
    //   example 1: strtotime('+1 day', 1129633200);
    //   returns 1: 1129719600
    //   example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);
    //   returns 2: 1130425202
    //   example 3: strtotime('last month', 1129633200);
    //   returns 3: 1127041200
    //   example 4: strtotime('2009-05-04 08:30:00 GMT');
    //   returns 4: 1241425800

    var parsed, match, today, year, date, days, ranges, len, times, regex, i, fail = false;

    if (!text) {
        return fail;
    }

    // Unecessary spaces
    text = text.replace(/^\s+|\s+$/g, '')
        .replace(/\s{2,}/g, ' ')
        .replace(/[\t\r\n]/g, '')
        .toLowerCase();

    // in contrast to php, js Date.parse function interprets:
    // dates given as yyyy-mm-dd as in timezone: UTC,
    // dates with "." or "-" as MDY instead of DMY
    // dates with two-digit years differently
    // etc...etc...
    // ...therefore we manually parse lots of common date formats
    match = text.match(
        /^(\d{1,4})([\-\.\/\:])(\d{1,2})([\-\.\/\:])(\d{1,4})(?:\s(\d{1,2}):(\d{2})?:?(\d{2})?)?(?:\s([A-Z]+)?)?$/);

    if (match && match[2] === match[4]) {
        if (match[1] > 1901) {
            switch (match[2]) {
                case '-':
                { // YYYY-M-D
                    if (match[3] > 12 || match[5] > 31) {
                        return fail;
                    }

                    return new Date(match[1], parseInt(match[3], 10) - 1, match[5],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
                case '.':
                { // YYYY.M.D is not parsed by strtotime()
                    return fail;
                }
                case '/':
                { // YYYY/M/D
                    if (match[3] > 12 || match[5] > 31) {
                        return fail;
                    }

                    return new Date(match[1], parseInt(match[3], 10) - 1, match[5],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
            }
        } else if (match[5] > 1901) {
            switch (match[2]) {
                case '-':
                { // D-M-YYYY
                    if (match[3] > 12 || match[1] > 31) {
                        return fail;
                    }

                    return new Date(match[5], parseInt(match[3], 10) - 1, match[1],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
                case '.':
                { // D.M.YYYY
                    if (match[3] > 12 || match[1] > 31) {
                        return fail;
                    }

                    return new Date(match[5], parseInt(match[3], 10) - 1, match[1],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
                case '/':
                { // M/D/YYYY
                    if (match[1] > 12 || match[3] > 31) {
                        return fail;
                    }

                    return new Date(match[5], parseInt(match[1], 10) - 1, match[3],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
            }
        } else {
            switch (match[2]) {
                case '-':
                { // YY-M-D
                    if (match[3] > 12 || match[5] > 31 || (match[1] < 70 && match[1] > 38)) {
                        return fail;
                    }

                    year = match[1] >= 0 && match[1] <= 38 ? +match[1] + 2000 : match[1];
                    return new Date(year, parseInt(match[3], 10) - 1, match[5],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
                case '.':
                { // D.M.YY or H.MM.SS
                    if (match[5] >= 70) { // D.M.YY
                        if (match[3] > 12 || match[1] > 31) {
                            return fail;
                        }

                        return new Date(match[5], parseInt(match[3], 10) - 1, match[1],
                                match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                    }
                    if (match[5] < 60 && !match[6]) { // H.MM.SS
                        if (match[1] > 23 || match[3] > 59) {
                            return fail;
                        }

                        today = new Date();
                        return new Date(today.getFullYear(), today.getMonth(), today.getDate(),
                                match[1] || 0, match[3] || 0, match[5] || 0, match[9] || 0) / 1000;
                    }

                    return fail; // invalid format, cannot be parsed
                }
                case '/':
                { // M/D/YY
                    if (match[1] > 12 || match[3] > 31 || (match[5] < 70 && match[5] > 38)) {
                        return fail;
                    }

                    year = match[5] >= 0 && match[5] <= 38 ? +match[5] + 2000 : match[5];
                    return new Date(year, parseInt(match[1], 10) - 1, match[3],
                            match[6] || 0, match[7] || 0, match[8] || 0, match[9] || 0) / 1000;
                }
                case ':':
                { // HH:MM:SS
                    if (match[1] > 23 || match[3] > 59 || match[5] > 59) {
                        return fail;
                    }

                    today = new Date();
                    return new Date(today.getFullYear(), today.getMonth(), today.getDate(),
                            match[1] || 0, match[3] || 0, match[5] || 0) / 1000;
                }
            }
        }
    }

    // other formats and "now" should be parsed by Date.parse()
    if (text === 'now') {
        return now === null || isNaN(now) ? new Date()
                .getTime() / 1000 | 0 : now | 0;
    }
    if (!isNaN(parsed = Date.parse(text))) {
        return parsed / 1000 | 0;
    }

    date = now ? new Date(now * 1000) : new Date();
    days = {
        'sun': 0,
        'mon': 1,
        'tue': 2,
        'wed': 3,
        'thu': 4,
        'fri': 5,
        'sat': 6
    };
    ranges = {
        'yea': 'FullYear',
        'mon': 'Month',
        'day': 'Date',
        'hou': 'Hours',
        'min': 'Minutes',
        'sec': 'Seconds'
    };

    function lastNext(type, range, modifier) {
        var diff, day = days[range];

        if (typeof day !== 'undefined') {
            diff = day - date.getDay();

            if (diff === 0) {
                diff = 7 * modifier;
            } else if (diff > 0 && type === 'last') {
                diff -= 7;
            } else if (diff < 0 && type === 'next') {
                diff += 7;
            }

            date.setDate(date.getDate() + diff);
        }
    }

    function process(val) {
        var splt = val.split(' '), // Todo: Reconcile this with regex using \s, taking into account browser issues with split and regexes
            type = splt[0],
            range = splt[1].substring(0, 3),
            typeIsNumber = /\d+/.test(type),
            ago = splt[2] === 'ago',
            num = (type === 'last' ? -1 : 1) * (ago ? -1 : 1);

        if (typeIsNumber) {
            num *= parseInt(type, 10);
        }

        if (ranges.hasOwnProperty(range) && !splt[1].match(/^mon(day|\.)?$/i)) {
            return date['set' + ranges[range]](date['get' + ranges[range]]() + num);
        }

        if (range === 'wee') {
            return date.setDate(date.getDate() + (num * 7));
        }

        if (type === 'next' || type === 'last') {
            lastNext(type, range, num);
        } else if (!typeIsNumber) {
            return false;
        }

        return true;
    }

    times = '(years?|months?|weeks?|days?|hours?|minutes?|min|seconds?|sec' +
        '|sunday|sun\\.?|monday|mon\\.?|tuesday|tue\\.?|wednesday|wed\\.?' +
        '|thursday|thu\\.?|friday|fri\\.?|saturday|sat\\.?)';
    regex = '([+-]?\\d+\\s' + times + '|' + '(last|next)\\s' + times + ')(\\sago)?';

    match = text.match(new RegExp(regex, 'gi'));
    if (!match) {
        return fail;
    }

    for (i = 0, len = match.length; i < len; i++) {
        if (!process(match[i])) {
            return fail;
        }
    }

    // ECMAScript 5 only
    // if (!match.every(process))
    //    return false;

    return (date.getTime() / 1000);
}

//根据页面的变化修改分享页面的内容
function share(title,desc,link,imgUrl) {
    if(title==undefined){
        title='碳蛋知--让营养食谱成为健身计划的标配'
    }
    if(desc==undefined){
        desc='“碳蛋知”是首款专门为运动人群进行营养配餐的专业配餐工具。其营养库中包含有大量科学性的营养套餐，同时系统具备智能化的营养套餐计算公式，简化了基础知识的部分，配合中国营养学会食谱库，帮助您更加专业的配餐，是您身边的运动营养服务专家。'
    }
    if(imgUrl==undefined){
        imgUrl="https://www.tandanzhi.com/src/images/logo-big.png"
    }

    if(link==undefined){
        link=location.href
    }

    wx.ready(function () {
        wx.onMenuShareTimeline({
            title: title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            // desc: vm.desc, // 分享描述
            success: function () {
                // 用户确认分享后执行的回调函数
                bottomAlert.close()
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                bottomAlert.close()
            }
        });

        wx.onMenuShareAppMessage({
            title: title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            desc: desc, // 分享描述
            tyle:"link",
            dataUrl:'',
            success: function () {
                // 用户确认分享后执行的回调函数
                bottomAlert.close()
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                bottomAlert.close()
            }
        });

        wx.onMenuShareQQ({
            title: title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            desc: desc, // 分享描述
            success: function () {
                // 用户确认分享后执行的回调函数
                bottomAlert.close()
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                bottomAlert.close()
            }
        });

        wx.onMenuShareWeibo({
            title: title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            desc: desc, // 分享描述
            success: function () {
                // 用户确认分享后执行的回调函数
                bottomAlert.close()
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                bottomAlert.close()
            }
        });

        wx.onMenuShareQZone({
            title: title, // 分享标题
            link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: imgUrl, // 分享图标
            desc: desc, // 分享描述
            success: function () {
                // 用户确认分享后执行的回调函数
                bottomAlert.close()
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
                bottomAlert.close()
            }
        });

    })


}